<?php

namespace app\yj\middleware;

use app\yj\model\RoleModel;
use app\yj\model\RuleModel;
use app\yj\model\UserModel;
use think\Request;
use think\Response;

class UserAuth
{
    private static $aes_key = '12aasa21dakqnbzv';

    public function handle($request, \Closure $next)
    {

        //获取token
        $token = $request->header('token');
        if ($token != '') {
            //判断token是否有效 用户是否该名称了
            $to_user = self::decrypt($token);

            //验证参数是否正确
            $user = UserModel::find($to_user['id']);
            if (!$user) {
                return Response::create(json_encode(['code' => 500, 'msg' => '用户不存在 请重新登录']));
            }

            if ($user->username != $to_user['username']) {
                return Response::create(json_encode(['code' => 500, 'msg' => '用户名错误,请重新登录']));
            }

            if ($user->password != $to_user['password']) {
                return Response::create(json_encode(['code' => 500, 'msg' => '用户密码不对 请重新登录']));
            }


            if ($user->roles != 0) {

                //检查权限
                $method = $request->method();
                $url = $request->url();
                $rules = self::getAllRule($user);
                $b = self::isNext($rules, $method, $url);
                if (!$b) return Response::create(json_encode(['code' => 401, 'msg' => '没有权限访问']));
                return $next($request);
            }
            return $next($request);

        } else {
            return Response::create(json_encode(['code' => 401, 'msg' => '没有登录!请登录用户']));
        }

    }

    /**
     * 解密
     * @param string $str 要解密的数据
     * @return string        解密后的数据
     */
    static public function decrypt($str)
    {

//        $decrypted = openssl_decrypt(base64_decode($str), 'AES-128-ECB', self::$aes_key, OPENSSL_RAW_DATA);
        $decrypted = base64_decode($str);

        return json_decode($decrypted, true);

    }

    static function getAllRule($user)
    {
        //获取权限数据
        $roles = $user['roles'];
        $rules = [];
        $role = RoleModel::find($user['roles']);

        if ($role != '') {
            foreach ($role['rules'] as $r) {
                $rule = RuleModel::find($r);
                if ($rule) {
                    array_push($rules, $rule['id']);
                }
            }
        };
        $rules = array_unique($rules);

        return $rules;
    }

    static function isNext($rules = [], $method, $url)
    {
        $url = str_replace('/bh/', '', $url);
        $rule = RuleModel::where('action', strtolower($url))->where('method', $method)->find();

        if ($rule) {

            //判断是否在权限数组里
            if (in_array($rule->id, $rules)) {
                return true;
            } else {
                return false;
            };
        } else {
            return false;
        }

    }
}
